<?php
/**
 *
 * PHP API 优惠券发放 控制器
 * @author jeff liu
 * powered by jeff liu 2012-02-29
 */

include API_ROOT_PATH . '/app/lib/SendCouponSimple.php';

class Single_user_send_coupon_baseApp extends ApiApp
{
    /**
     * 是否可以向同一用户重复发放优惠券
     * @var boolean
     */
    public $duplicate = false;


    /**
     * 是否排除商家用户
     * @var boolean
     */
    public $escape_store = true;
    /**
     *
     * 活动状态
     * @var boolean
     */
    public $hd_status = true;

    /**
     * 记录log对应的model
     * @var object
     */
    public $log_model = null;


    /**
     * 是否判断用户真是存在
     * @var boolean
     */
    public $real_user = true;

    /**
     * 是否验证优惠券id信息
     * @var boolean
     */
    public $verify_coupon = true;
    /**
     *
     * 发送通知模板
     * @var array
     */
    public $template = null;

    function __construct()
    {
        $this->Single_user_send_coupon_baseApp();
    }

    function Single_user_send_coupon_baseApp()
    {
        parent::__construct();

        $this->init();
    }

    function init()
    {
        $this->log_model = null;

        $this->template = array(
            //站内信配置
            'message_template' => array(
                'send' => true, //是否发送
                'template' => "tobuyer_get_coupon_notify", //发送模板
            ),
            //邮件配置
            'mail_template' => array(
                'send' => false, //是否发送
                'template' => "tobuyer_get_coupon_notify", //发送模板
            ),
            //手机短信配置
            'mobile_message_template' => array(
                'send' => false, //是否发送
                'template' => "tobuyer_get_coupon_notify", //发送模板
            ),
        );
    }


    /**
     * 完成抽奖结果并发送优惠券
     * powere by jeff liu 2012-02-29
     */
    function apiFinishLottery()
    {
        /**
         * coupon_sn 发送结构
         * @var boolean
         */
        $send_result = true;

        /**
         * 发送的coupon_sn
         * @var mixed
         */
        $coupon_sn = array();

        /**
         * 返回信息
         * @var string
         */
        $msg = '';

        /**
         * 返回状态码
         * @var string
         */
        $code = '';


        /**
         * 活动结束不能再发送优惠券 直接返回错误 start
         */
        if (!$this->hd_status) {
            $ret_url = SITE_URL . '/index.php?app=my_coupon';
            $send_result = false;
            $return_data = array(
                'code' => 2,
                'msg' => '抽奖活动已经结束！！！请联系相关人员。',
                'send_result' => $send_result,
                'coupon_sn' => $coupon_sn,
                'ret_url' => urlencode($ret_url)
            );
            $this->echo_result($return_data);
            exit;
        }
        /**
         * 活动结束不能再发送优惠券 直接返回错误 end
         */


        /**
         * 获得user_id start
         */
        $user_id = $this->get_user_id();

        if (empty($user_id)) {
            $send_result = false;
            $msg = '用户信息丢失';
            $code = 3;

            $coupon_sn[] = 'null';
        }

        /**
         * 获得user_id end
         */

        /**
         * 过滤已经发送过优惠券的用户 start
         */
        if (!$this->duplicate && !empty($user_id)) {
            $ori_user_id = $user_id;
            $user_id = $this->escape_duplicate_user_id($user_id);

            if (empty($user_id)) {
                $send_result = false;
                $msg = '当前用户已经获得过该活动的优惠券';
                $code = 4;

                $coupon_sn[$ori_user_id] = 'null';
            }

        }
        /**
         * 过滤已经发送过优惠券的用户 end
         */


        /**
         * 排除用户列表中的商家用户 （商家用户不能获得优惠券） start
         */
        if ($this->escape_store && !empty($user_id)) {
            $ori_user_id = $user_id;
            $user_id = $this->escape_store_from_user_id($user_id);

            if (empty($user_id)) {
                $send_result = false;
                $msg = '当前用户为商家用户，不能为其发送优惠券';
                $code = 5;

                $coupon_sn[$ori_user_id] = 'null';
            }
        }
        /**
         * 排除用户列表中的商家用户 （商家用户不能获得优惠券） end
         */

        /**
         * 排除掉不是商城用户的user_id
         */
        if ($this->real_user && !empty($user_id)) {
            $ori_user_id = $user_id;
            $user_id = $this->escape_fake_user($user_id);

            if (empty($user_id)) {
                $send_result = false;
                $msg = '用户不存在';
                $code = 6;

                $coupon_sn[$ori_user_id] = 'null';
            }
        }

        if (!empty($user_id)) { //用户信息没有问题
            /**
             * 获得对应的coupon_id start
             */
            $coupon_id = $this->get_coupon_ids();

            if (is_array($coupon_id)) { //去重
                $coupon_id = array_unique($coupon_id);
            }
            /**
             * 获得对应的coupon_id end
             */


            if (empty($coupon_id)) {
                $send_result = false;
                $msg = '优惠券ID不存在';
                $code = 7;

                $coupon_sn[$user_id] = 'null';
            }

            if (!empty($coupon_id) && $this->verify_coupon) {
                $ori_coupon_id = $coupon_id;

                $coupon_id = $this->escape_fake_coupon($coupon_id);

                if (empty($coupon_id)) {
                    $send_result = false;
                    $msg = '优惠券ID不正确';
                    $code = 8;

                    $coupon_sn[$user_id] = 'null';
                }
            }
        }


        if (empty($msg)) { //没有出现错误信息
            /**
             * 发放优惠券 start
             */
            $coupon_sn = $this->send_coupon($user_id, $coupon_id, $this->template);

            if ($coupon_sn === '3') {
                $send_result = false;
                $msg = '优惠券ID不存在或者优惠券已过期';
                $code = 9;

                $coupon_sn[$user_id] = 'null';
            } else {
                $send_result = true;
                $code = 1;
                $msg = '优惠券发放成功';
            }
        }

        /**
         * 添加发放优惠券记录 start
         */

        $description = 'cp315优惠券发放';

        $send_result = $this->log_send_coupon_result($coupon_sn, $code, $msg, $description);
        /**
         * 添加发放优惠券记录 end
         */

        //查询优惠券的地址
        $ret_url = SITE_URL . '/index.php?app=my_coupon';
        $return_data = array(
            'code' => $code,
            'msg' => $msg,
            'coupon_sn' => $coupon_sn,
            'send_result' => $send_result,
            'ret_url' => urlencode($ret_url)
        );

        $this->echo_result($return_data);
    }

    /**
     * 排除掉不正确的coupon_id
     * @author jeff liu 2012-03-06
     * @param mixed $user_id_list
     */
    function escape_fake_coupon($coupon_id_list)
    {
        $final_coupon_id_list = array();

        if (!empty($coupon_id_list)) {
            $coupon_mod =& m('coupon');

            if (is_string($coupon_id_list)) {
                $sql = sprintf(
                    'SELECT coupon_id FROM %s WHERE coupon_id=%.0f',
                    $coupon_mod->table,
                    (float)$coupon_id_list
                );
            } else {
                $sql = sprintf(
                    'SELECT coupon_id FROM %s WHERE coupon_id IN (%s)',
                    $coupon_mod->table,
                    implode(',', $coupon_id_list)
                );
            }
            $coupon_infos = $coupon_mod->getAll($sql);
            if (!empty($coupon_infos) && is_array($coupon_infos)) {
                foreach ($coupon_infos as $coupon_info) {
                    $final_coupon_id_list[] = $coupon_info['coupon_id'];
                }
            }
        }

        return $final_coupon_id_list;
    }

    /**
     * 排除掉不是商城用户的user_id
     * @author jeff liu 2012-03-06
     * @param int $user_id
     */
    function escape_fake_user($user_id)
    {
        if (!empty($user_id)) {
            $member_mod =& m('member');
            $sql = sprintf('SELECT `user_id` FROM %s WHERE `user_id` = %.0f', $member_mod->table, (float)$user_id);
            $member_infos = $member_mod->getAll($sql);

            if (empty($member_infos)) {
                $user_id = null;
            }
        }

        return $user_id;
    }


    /**
     * 获得user_id
     * @author jeff fliu 2012-03-01
     */
    function get_user_id()
    {
        $user_id = $_REQUEST['user_id'] ? sprintf('%.0f', (int)$_REQUEST['user_id']) : 0;

        if (empty($user_id)) {
            $umpid = $this->get_umpid();

            $user_id = $this->get_user_id_by_umpid($umpid);
        }

        return $user_id;
    }

    /**
     * 获得umpid
     * @author jeff liu 2012-02-29
     */
    function get_umpid()
    {
        $umpid = $_REQUEST['umpid'] ? trim($_REQUEST['umpid']) : '';

        return $umpid;
    }

    /**
     * 是否需要排除当前用户
     * @author jeff liu 2012-03-01
     * @param int $user_id
     */
    function escape_duplicate_user_id($user_id)
    {
        $final_user_id = null;

        $sent_coupon_user_id = $this->log_model->escape_duplicate_user_id($user_id);

        if (empty($sent_coupon_user_id)) { //当前用户还没有发送过优惠券
            $final_user_id = $user_id;
        }

        return $final_user_id;
    }

    /**
     * 获得优惠券id
     * @author jeff liu 2012-02-29
     */
    function get_coupon_ids()
    {
        $coupon_ids = array();


        return $coupon_ids;
    }


    /**
     * 根据umpid获得该用户在商城对应的user_id
     * @author jeff liu
     * @param string $umpid
     */
    function get_user_id_by_umpid($umpid = 0)
    {
        $member_mod =& api_model('member');
        $user_id = $member_mod->get_user_id_by_umpid($umpid);
    }

    /**
     * 发送优惠券
     * @author jeff liu 2012-02-29
     * @param mixed $user_ids 发送优惠券对象
     * @param mixed $coupon_ids 发送优惠券对象
     * @param array $template 通知载体配置项
     */
    function send_coupon($user_ids, $coupon_ids, $template = array())
    {
        $template = $template ? $template : $this->template;

        $coupon_send = new SendCouponSimple(
            array(
                'coupon_id' => $coupon_ids,
                'login_verify' => false, //是否验证登录
                'user_id' => $user_ids,
            ),
            $template
        );
        $rst = $coupon_send->send_coupon();
        if ($rst === true) {
            $coupon_sn = $coupon_send->get_sent_coupon_sn();
        } else {
            $coupon_sn = '3';
        }
        return $coupon_sn;
    }

    /**
     * 记录优惠券发放结果
     * @author jeff liu 2012-03-06
     * @param array $coupon_sn 优惠券信息（数字的key为用户id）
     * @param int $code 状态码
     * @param string $msg 发送优惠券结果信息
     * @param string $description 描述信息
     */
    function log_send_coupon_result($coupon_sn, $code, $msg, $description)
    {
        $this->log_model->log_send_coupon_result($coupon_sn, $code, $msg, $description);
        return true;
    }

    /**
     * 过滤用户id列表中的商家用户
     * @author jeff liu 2012-03-06
     * @param array $user_id_list
     */
    function escape_store_from_user_id($user_id)
    {
        $store_mod = & m('store');

        //获得用户列表中的商家用户
        $sql = sprintf(
            'SELECT store_id
		            	FROM %s
		            	WHERE store_id = %.0f',
            $store_mod->table,
            (float)$user_id
        );
        $seller_info = $store_mod->getAll($sql);

        if (!empty($seller_info)) { //当前用户为商家用户
            $user_id = null;
        }

        return $user_id;
    }
}
